package com.lovely602.langchain4j.persistent.config;


import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * 知识出处：https://docs.langchain4j.dev/tutorials/chat-memory#persistence
 *
 * @author lizhixing
 */
@Configuration
public class RedisChatMemoryStore implements ChatMemoryStore {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    private static final String CHAT_MEMORY_PREFIX = "CHAT_MEMORY:";

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {

        String retValue = stringRedisTemplate.opsForValue().get(CHAT_MEMORY_PREFIX + memoryId);

        return ChatMessageDeserializer.messagesFromJson(retValue);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {

        stringRedisTemplate.opsForValue().set(CHAT_MEMORY_PREFIX + memoryId, ChatMessageSerializer.messagesToJson(messages));
    }

    @Override
    public void deleteMessages(Object memoryId) {
        stringRedisTemplate.delete(CHAT_MEMORY_PREFIX + memoryId);
    }
}
